from fastapi import APIRouter
from pydantic import BaseModel

from DataModels.database import User
from DataModels.share import RespInfo, RespResultCode, StatusInfo
from utils.token import decode_token


class PasswordRequest(BaseModel):
    code: str
    password: str


password_router = APIRouter(prefix="/password")


@password_router.post("")
async def password(data: PasswordRequest):
    tk = decode_token(data.code)
    phone = tk.phone
    user = await User.find_one(User.phone == phone)
    if not user:
        return RespInfo(
            status=StatusInfo(
                code=RespResultCode.PhoneNotFound,
                msg="未找到手机号",
            )
        )
    user.password = data.password
    await user.save()  # type: ignore
    return RespInfo(
        status=StatusInfo(
            code=RespResultCode.Success,
            msg="修改成功",
        ),
    )
